/*
* 事件监听器：用于发送通知，监听通知，全局唯一
* */
class EventListener{
    static getInstance(){
        if (!EventListener._instance) {
            EventListener._instance = new EventListener();
        }
        return EventListener._instance;
    }
    constructor(){
        this.register = {};
    }
    /**
     *  target: 监听器绑定的对象（类名字符串） 例:"EventListener"
     *  name: 监听消息的ID（string/number） 例:2001 / Refresh_card
     *  method: 监听的方法
     */
    addListener(target, name, method) {
        if (!this.register.hasOwnProperty(target)) {
            this.register[target] = {};
        }
        if (!this.register[target].hasOwnProperty(name)) {
            this.register[target][name] = [];
        }
        this.register[target][name].push(method);
    }
    removeListener(target) {
        console.log("off handler target = " + target);
        if (this.register.hasOwnProperty(target)) {
            delete this.register[target];
        }
    }
    postMessage(obj) {
        // console.log("post: " + JSON.stringify(obj));
        let name = obj.code;
        let data = obj.data;
        for (let id in this.register) {
            let obj = this.register[id];
            if (obj.hasOwnProperty(name)) {
                let handlerList = obj[name];
                for (let j = 0; j < handlerList.length; j++) {
                    (function (j) {
                        handlerList[j](data);
                    })(j);
                }
            }
        }
    }
}
EventListener._instance = null;
module.exports = EventListener;